package com.formiaomiao.demain.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.model.UserBean;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_user)
    EditText etUser;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.tv_forget)
    TextView tvForget;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.btn_login)
    Button btnLogin;

    LoadingDialog loadingDialog;
    UserBean userBean = new UserBean();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        ViewInit();
    }

    public void ViewInit() {
        tvForget.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        loadingDialog = new LoadingDialog(this);
        if (!PreferenceUtils.getBoolean(this, PreferenceValues.CHECKPERMISSION)) {
            CheckPermissionInit();
        } else {
            if (!XXPermissions.isHasPermission(this, Permission.Group.STORAGE) ||
                    !XXPermissions.isHasPermission(this, Permission.CAMERA) ||
                    !XXPermissions.isHasPermission(this, Permission.Group.LOCATION)) {
                ToastUtils.show(this, "需要提供权限，请前往设置界面给予权限");
                XXPermissions.gotoPermissionSettings(this);
            }
        }
    }

    /**
     * 登录操作
     *
     * @param user
     * @param password
     */
    public void LoginInit(final String user, final String password) {
        loadingDialog.show();
        HttpParams params = new HttpParams();
        params.put("userName", user);
        params.put("passWord", password);
        OkGo.<String>post(BaseUrl.USERSIGNIN).params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                userBean = gson.fromJson(response.body(), UserBean.class);
                if (response.body().contains("200")) {
                    PreferenceUtils.setString(LoginActivity.this, PreferenceValues.PASSWORD, etPwd.getText().toString().trim());
                    PreferenceUtils.setString(LoginActivity.this, PreferenceValues.USERNAME, etUser.getText().toString().trim());
                    PreferenceUtils.setString(LoginActivity.this, PreferenceValues.TOKEN,"Bearer " + userBean.getData().getToken());
                    StaticValues.nickname = userBean.getData().getNickName();
                    StaticValues.userid = userBean.getData().getId();
                    StaticValues.username = userBean.getData().getUserName();
                    if (userBean.getData().getUserHead() == null) {
                        StaticValues.userhead = "";
                    } else {
                        StaticValues.userhead = userBean.getData().getUserHead();
                    }
                    RingLogin(user,password);
                    ToastUtils.show(LoginActivity.this, "登录成功");
                } else {
                    ToastUtils.show(LoginActivity.this, "登录失败," + userBean.getMsg());
                    System.out.println(userBean.getMsg());
                }
                loadingDialog.dismiss();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * 登录环信
     * @param userName
     * @param password
     */
    public void RingLogin(String userName,String password){
        EMClient.getInstance().login(userName,password,new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.d("main", "登录聊天服务器成功！");
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("main", "登录聊天服务器失败！");
            }
        });
    }

    @OnClick({R.id.tv_forget, R.id.tv_register, R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_forget:                                                    //忘记密码
                startActivity(new Intent(this, ForgetActivity.class));
                break;
            case R.id.tv_register:                                                  //注册
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.btn_login:                                                    //登录
                if (etUser.getText().toString().isEmpty()) {
                    ToastUtils.show(this, "请输入手机号");
                } else if (etPwd.getText().toString().isEmpty()) {
                    ToastUtils.show(this, "请输入密码");
                } else {
                    LoginInit(etUser.getText().toString(), etPwd.getText().toString());
                }
                break;
        }
    }

    /**
     * 验证权限
     */
    public void CheckPermissionInit() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.LOCATION)
                .permission(Permission.RECORD_AUDIO)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        PreferenceUtils.setBoolean(LoginActivity.this, PreferenceValues.CHECKPERMISSION, true);
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        ToastUtils.show(LoginActivity.this, "必要权限未提供，app即将关闭");
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        finish();
                    }
                });
    }


}
